package com.wg.msorderds.entity;



import com.wg.msorderds.entity.Ordertb;
import com.wg.msorderds.service.IOrdertbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class OrderTimeoutTask {

    @Autowired
    private IOrdertbService ordertbService;

    /**
     * 每分钟检查超时未支付订单
     */
    @Scheduled(cron = "0 * * * * ?") // 每分钟执行一次
    public void checkTimeoutOrders() {
        try {
            // 设置超时时间为10分钟
            int timeoutMinutes = 10;
            List<Ordertb> timeoutOrders = ordertbService.getTimeoutUnpaidOrders(timeoutMinutes);

            System.out.println("发现 " + timeoutOrders.size() + " 个超时订单");

            for (Ordertb order : timeoutOrders) {
                // 自动取消订单
                boolean result = ordertbService.cancelOrder(order.getId());
                if (result) {
                    System.out.println("订单 " + order.getId() + " 已超时自动取消");
                } else {
                    System.out.println("订单 " + order.getId() + " 取消失败");
                }
            }
        } catch (Exception e) {
            System.err.println("检查超时订单失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
